package com.hb.trade.server.project.section.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.enums.ProblemStatusEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.dto.ClarifyConfirmDTO;
import com.hb.core.pojo.project.section.dto.ClarifyDTO;
import com.hb.core.pojo.project.section.dto.ClarifyTemplateDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.Clarify;
import com.hb.core.pojo.project.section.entity.ClarifySection;
import com.hb.trade.server.project.proj.service.ProjectService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.section.service.raw.ClarifyConfirmService;
import com.hb.trade.server.project.section.service.raw.ClarifySectionService;
import com.hb.trade.server.project.section.service.raw.ClarifyService;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 澄清答疑表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-10-09
 */
@RestController
public class ClarifyController {

    protected final ClarifyService clarifyService;
    protected final ClarifySectionService clarifySectionService;
    protected final ClarifyConfirmService clarifyConfirmService;
    protected final BidSectionService bidSectionService;
    protected final ProjectService projectService;

    public ClarifyController(ClarifyService clarifyService,
                             ClarifySectionService clarifySectionService,
                             ClarifyConfirmService clarifyConfirmService,
                             ProjectService projectService,
                             BidSectionService bidSectionService) {
        this.clarifyService = clarifyService;
        this.clarifySectionService = clarifySectionService;
        this.clarifyConfirmService = clarifyConfirmService;
        this.bidSectionService = bidSectionService;
        this.projectService = projectService;
    }

    /**
     * 保存澄清补遗
     *
     * @param clarify
     * @return
     */
    @PostMapping("/clarify/saveClarify")
    @Transactional(rollbackFor = Exception.class)
    public Message<ClarifyDTO> saveClarify(@RequestBody ClarifyDTO clarify) {
        String msg = clarify.paramsValid();
        if (StrUtil.isNotEmpty(msg)){
            return MsgUtil.fail(msg);
        }
        List<ClarifySection> clarifySectionList = clarify.getSectionList();
        if (CollUtil.isEmpty(clarifySectionList)) {
            return MsgUtil.fail("请先关联标段");
        }
        //判断响应文件递交截止时间/开标时间是否为空，决定是否同步标段相关属性
        Boolean updateBidOpeningTimeFlag = false;
        if (null != clarify.getBidOpeningTime()) {
            updateBidOpeningTimeFlag = true;
        }
        clarify.buildBaseData(1);
        // 取消保存按钮，直接扫码签章，所以状态直接为已发出 2022-2-26 12:48:26 宋瑜提出
        clarify.setStatus(ProblemStatusEnum.ISSUED.getCode());
        Long id = clarify.getId();
        //处理澄清补遗-标段关联表
        for (ClarifySection clarifySection : clarifySectionList) {
            clarifySection.setId(null);
            clarifySection.buildBaseData(1);
            clarifySection.setClarifyId(id);

            //构造标段实体，同步开标时间
            if (updateBidOpeningTimeFlag) {
//                BidSection section = bidSectionService.getById(clarifySection.getSectionId());
//                AbstractProject project = projectService.getById(section.getProjectId());
                // 依法招标
//                if (project.getProjectModule().equals(ProjectModuleEnum.CONSTRUCTION_PROJECT.getCode())){
//                    if (section.getDocumentSaleStartTime().getTime() > clarify.getBidOpeningTime().getTime()){
//                        return MsgUtil.fail("提交投标文件截止之日距招标文件开始发出之日起至不得少于二十日");
//                    }
//                    long day = (clarify.getBidOpeningTime().getTime() - section.getDocumentSaleStartTime().getTime()) / (24 * 60 * 60 * 1000);
//                    if (day<20){
//                        return MsgUtil.fail("提交投标文件截止之日距招标文件开始发出之日起至不得少于二十日");
//                    }
//                }else {
//                    if (section.getDocumentSaleStartTime().getTime() > clarify.getBidOpeningTime().getTime()){
//                        return MsgUtil.fail("采购类招标提交投标文件截止之日距招标文件开始发出之日起至不得少于五日");
//                    }
//                    long day = (clarify.getBidOpeningTime().getTime() - section.getDocumentSaleStartTime().getTime()) / (24 * 60 * 60 * 1000);
//                    if (day<5){
//                        return MsgUtil.fail("采购类招标提交投标文件截止之日距招标文件开始发出之日起至不得少于五日");
//                    }
//                }

                BidSection bidSection = new BidSection();
                bidSection.setId(clarifySection.getSectionId());
                bidSection.setOpenBidTime(clarify.getBidOpeningTime());
                bidSectionService.updateById(bidSection);


            }
        }
        clarifySectionService.saveBatch(clarifySectionList);
        //保存澄清/补疑
        boolean result = clarifyService.save(clarify);
        return result? MsgUtil.success(clarify): MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 招标人查询澄清/补疑列表
     *
     * @param clarifyDTO
     * @return
     */
    @PostMapping("/clarify/findClarifyList")
    public Message<PageResult> findClarifyList(@RequestBody ClarifyDTO clarifyDTO) {
        QueryWrapper<Clarify> clarifyQueryWrapper = new QueryWrapper<>();
        Clarify clarify = new Clarify();
        clarifyDTO.to(clarify);
        Page<Clarify> pages = clarify.pages();
        //招标人查询澄清/补疑列表
        clarifyQueryWrapper.lambda().eq(Clarify::getProjectId, clarifyDTO.getProjectId()).orderByDesc(Clarify::getCreateTime);

        IPage<Clarify> clarifyIPage = clarifyService.page(pages, clarifyQueryWrapper);
        // 返回DTO
        IPage<ClarifyDTO> clarifyPage = new Page<>();
        clarifyPage.setPages(clarifyIPage.getPages());
        clarifyPage.setCurrent(clarifyIPage.getCurrent());
        clarifyPage.setSize(clarifyIPage.getSize());
        clarifyPage.setTotal(clarifyIPage.getTotal());

        List<ClarifyDTO> records = new ArrayList<>();
        for (Clarify data: clarifyIPage.getRecords()){
            ClarifyDTO dto = data.to(ClarifyDTO.class);
            // 查询标段名称
//            LambdaQueryWrapper<ClarifySection> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(ClarifySection::getClarifyId, data.getId());
//            List<ClarifySection> clarifySection = clarifySectionService.list(queryWrapper);
            List<BidSectionDTO> bidSectionList = bidSectionService.listBidSectionByClarify(data.getId());
            List<ClarifySection> clarifySection = new ArrayList<>();
            for (BidSectionDTO bidSectionDTO: bidSectionList){
                clarifySection.add(bidSectionDTO.to(ClarifySection.class));
            }
            dto.setSectionList(clarifySection);
            records.add(dto);
        }
        clarifyPage.setRecords(records);

        List<ClarifyDTO> clarifyDtoList = ClarifyDTO.changeClarifyDto(clarifyIPage.getRecords());
        for (ClarifyDTO clarifyDto : clarifyDtoList) {
           //查询总数
           int totalCount = clarifyConfirmService.findStatusCount(clarifyDto.getId(),-1);
           //已确认的个人
           int confirmedCount = clarifyConfirmService.findStatusCount(clarifyDto.getId(), LogicEnum.YES.getCode());
           //设置 未确认/已确认/总数
           clarifyDto.setStatusCount((totalCount - confirmedCount) + "/" + confirmedCount + "/" + totalCount);
        }
        return MsgUtil.success(PageResult.get(clarifyPage));
    }

    /**
     * 澄清补遗签章
     *
     * @param clarifyDTO
     * @return
     */
    @PostMapping("/clarify/signature")
    public Message signature(@RequestBody ClarifyDTO clarifyDTO) {
        if (null == clarifyDTO || null == clarifyDTO.getId() || null == clarifyDTO.getClarifyFileSignature()) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        Boolean result = clarifyService.updateById(clarifyDTO);
        return MsgUtil.msg(result);
    }

    /**
     * 招标人发出澄清/补疑
     *
     * @param id
     * @return
     */
    @PostMapping("/clarify/sendClarify")
    public Message sendClarify(@RequestParam Long id) {
        Clarify clarify = clarifyService.getById(id);
        if(null == clarify){
            return MsgUtil.fail("澄清/补疑不存在,请刷新列表");
        }
        if (ProblemStatusEnum.TO_BE_ISSUED.getCode() != clarify.getStatus()){
            return MsgUtil.fail("只有待发出状态的澄清/补疑才能发出");
        }
        if (null == clarify.getClarifyFileSignature()) {
            return MsgUtil.fail("还未签章，禁止操作");
        }
        Clarify newClarify = new Clarify();
        newClarify.setId(id);
        newClarify.setStatus(ProblemStatusEnum.ISSUED.getCode());
        Boolean result = clarifyService.updateById(newClarify);
        return MsgUtil.msg(result);
    }

    /**
     * 投标人查询澄清/补疑列表
     *
     * @param clarifyDTO
     * @return
     */
    @PostMapping("/clarify/findBidderClarifyList")
    public Message<PageResult<ClarifyDTO>> findBidderClarifyList(@RequestBody ClarifyDTO clarifyDTO) {
        PageResult<ClarifyDTO> clarifyPage = clarifyService.findBidderClarifyList(clarifyDTO);
        if (CollUtil.isEmpty(clarifyPage.getRecords())){
            return MsgUtil.success(clarifyPage);
        }
        for (ClarifyDTO record : clarifyPage.getRecords()) {
            List<ClarifySection> clarifySectionList = clarifySectionService.listClarifyConfirm(record.getId());
            record.setSectionList(clarifySectionList);
        }
        return MsgUtil.success(clarifyPage);
    }

    /**
     * 投标人确认
     *
     * @param clarifyConfirm
     * @return
     */
    @PostMapping("/clarify/confirmClarify")
    public Message confirmClarify(@RequestBody ClarifyConfirmDTO clarifyConfirm) {

        clarifyConfirm.setConfirmFlag(LogicEnum.YES.getCode());
        if (clarifyConfirm.getId() == null){
            int countConfirmFlag = clarifyConfirmService.getCountConfirmFlag(clarifyConfirm.getClarifyId(), clarifyConfirm.getTenderId());
            if (countConfirmFlag > 0){
                return MsgUtil.fail("不能重复回执澄清");
            }
            clarifyConfirm.buildBaseData(1);
        }else {
            clarifyConfirm.buildBaseData(2);

        }
        clarifyConfirmService.saveOrUpdate(clarifyConfirm);
        return MsgUtil.success();
    }

    /**
     * 根据主键Id查看澄清/补疑详情
     *
     * @param id
     * @return
     */
    @GetMapping("/clarify/findClarifyById")
    public Message<ClarifyDTO> findClarifyById(@RequestParam Long id) {
        QueryWrapper<Clarify> clarifyQueryWrapper = new QueryWrapper<>();
        clarifyQueryWrapper.eq("id", id);
        Clarify clarify = clarifyService.getOne(clarifyQueryWrapper);
        if (null == clarify){
            return MsgUtil.fail("未获取到相关信息");
        }
        ClarifyDTO clarifyDto = clarify.to(ClarifyDTO.class);
        List<ClarifySection> clarifySectionList = clarifySectionService.list(new LambdaQueryWrapper<ClarifySection>()
                .eq(ClarifySection::getClarifyId, clarify.getId()));
        clarifyDto.setSectionList(clarifySectionList);
        return MsgUtil.success(clarifyDto);
    }

    /**
     * @param clarifyDTO:
     * @Description:招标人查看澄清补疑回执列表
     * @Author: zhongdl
     * @Date:2022/5/20 11:35

     * @return: {@link org.fzzn.core.model.msg.Message<com.hb.core.pojo.parent.PageResult<com.hb.core.pojo.project.section.dto.ClarifyConfirmDTO>> }
     **/
    @PostMapping("/clarify/pageClarifyConfirm")
    public Message<PageResult<ClarifyConfirmDTO>> pageClarifyConfirm(@RequestBody ClarifyDTO clarifyDTO) {
        List<ClarifySection> clarifySections = clarifySectionService.listClarifyConfirm(clarifyDTO.getId());
        if (CollUtil.isEmpty(clarifySections)){
            return MsgUtil.success(PageResult.get());
        }
        clarifyDTO.setSectionList(clarifySections);
        PageResult<ClarifyConfirmDTO> pageResult = clarifyConfirmService.pageClarifyConfirm(clarifyDTO);
        return MsgUtil.success(pageResult);
    }

    /**
     * @Description: 查询投标人澄清回执word模版需要的信息
     *
     * { 澄清代理公司、 项目名称、 当前时间(xxxx年xx月xx日)、 回执企业 }
     *
     * @author yuezheng
     * @param
     * @return org.fzzn.core.model.msg.ResponseDto
     * @date 2022/5/23 13:48
     */
    @PostMapping("/clarify/template")
    public Message<ClarifyTemplateDTO> findClarifyTemplateInfo(@RequestBody ClarifyDTO clarifyDTO){
       return MsgUtil.msg(clarifyService.findClarifyTemplateInfo(clarifyDTO));
    }

}
